package com.xinzhi.service.impl;

import com.xinzhi.mapper.BankCardMapper;
import com.xinzhi.mapper.PhoneTransferMapper;
import com.xinzhi.mapper.TransferUserMapper;
import com.xinzhi.pojo.BankCard;
import com.xinzhi.pojo.PhoneTransfer;
import com.xinzhi.pojo.TransferUser;
import com.xinzhi.service.ITransferService;
import com.xinzhi.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Administrator
 */
@Service
public class PhoneServiceImpl implements ITransferService {

    @Autowired
    private PhoneTransferMapper phoneTransferMapper;

    @Autowired
    private TransferUserMapper transferUserMapper;

    @Autowired
    private BankCardMapper bankCardMapper;

    private static final String BANK_ACCOUNT_REGEX = "^\\d{16,19}$";
    private static final long TRANSFER_DELAY_MS = 30000; // 30秒

    @Override
    @Transactional
    public Result transfer(String senderBankAccount, String receiverName, String receiverPhoneNumber, Double amount, String description) {
        if (!isValidBankAccount(senderBankAccount)) {
            return Result.error("发送者银行卡号格式不正确：" + senderBankAccount);
        }

        // 查询发送者信息
        TransferUser sender = transferUserMapper.selectByBankAccount(senderBankAccount);
        if (sender == null) {
            return Result.error("发送者账户不存在：" + senderBankAccount);
        }

        // 查询接收者信息
        BankCard receiver = bankCardMapper.selectByPhone(receiverPhoneNumber);
        if (receiver == null) {
            return Result.error("接收者账户不存在：" + receiverPhoneNumber);
        }

        // 更新发送者余额
        BigDecimal amountBigDecimal = BigDecimal.valueOf(amount);
        BigDecimal senderNewBalance = sender.getBalance().subtract(amountBigDecimal);
        if (senderNewBalance.compareTo(BigDecimal.ZERO) < 0) {
            return Result.error("发送者余额不足");
        }
        sender.setBalance(senderNewBalance);
        transferUserMapper.updateBalance(sender.getId(), senderNewBalance);

        // 更新接收者余额
        BigDecimal receiverNewBalance = new BigDecimal(receiver.getCardMoney()).add(amountBigDecimal);
        receiver.setCardMoney(receiverNewBalance.toString());
        bankCardMapper.updateBalance(receiver.getCardId(), receiverNewBalance);

        // 创建转账记录
        PhoneTransfer phoneTransfer = new PhoneTransfer();
        phoneTransfer.setSenderBankAccount(senderBankAccount);
        phoneTransfer.setReceiverName(receiverName);
        phoneTransfer.setReceiverPhoneNumber(receiverPhoneNumber);
        phoneTransfer.setAmount(amount);
        phoneTransfer.setTransferTime(new Timestamp(System.currentTimeMillis()));
        phoneTransfer.setStatus("待处理");
        phoneTransfer.setDescription(description);

        phoneTransferMapper.insert(phoneTransfer);

        // 定时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                processPhoneTransfer(phoneTransfer.getId());
            }
        }, TRANSFER_DELAY_MS);

        return Result.ok("成功").put("status", "pending");
    }

    @Transactional
    public void processPhoneTransfer(Long transferId) {
        PhoneTransfer phoneTransfer = phoneTransferMapper.selectById(transferId);
        if (phoneTransfer == null) {
            throw new RuntimeException("转账记录不存在");
        }

        // 更新转账记录状态为完成并设置到账时间为 transferTime 加 30 秒
        phoneTransfer.setStatus("完成");
        phoneTransfer.setArrivalTime(new Timestamp(phoneTransfer.getTransferTime().getTime() + TRANSFER_DELAY_MS));
        phoneTransferMapper.updateById(phoneTransfer);
    }

    private boolean isValidBankAccount(String bankAccount) {
        return bankAccount != null && bankAccount.matches(BANK_ACCOUNT_REGEX);
    }
}
